var app = getApp();
var vp = require('../../resource/js/vp.js');
Page({
  data: {
    isEdit: false, // 是否为编辑模式
    planId: null, // 编辑时的计划ID
    
    // 表单数据
    formData: {
      medication_name: '',
      start_date: '',
      length: '1',
	  duration:'1天',
      method: '',
      scheme: 0, // 0-每天几次 1-几天一次 2-几小时一次
      num: '',
	  frequency:'',
      times: [''],
      dosage: '',
	  metering:'',
	  metering_unit:'',
      guidance: '',
      remark: ''
    },
    
    // 选择器数据
   
    currentPerson: {  },
    minDate: '2020-01-01',
    lengths: ['3', '5', '7', '10', '14', '30'],
    methods: ['口服', '外用', '注射', '含服', '贴敷'],
    dailyFrequencies: ['每天1次', '每天2次', '每天3次', '每天4次'],
    dayIntervals: ['每2天1次', '每3天1次', '每周1次', '每周2次'],
    hourIntervals: ['每4小时1次', '每6小时1次', '每8小时1次', '每12小时1次'],
    dosages: [],
    guidances: [
      { name: '餐前', value: 'before' },
      { name: '餐后', value: 'after' },
      { name: '空腹', value: 'empty' },
      { name: '随餐服用', value: 'with' },
      { name: '睡前', value: 'sleep' }
    ],
	// 剂量单位
	dosageUnits: [
	  { label: '片', value: '片' },
	  { label: '克', value: '克' },
	  { label: '毫克', value: '毫克' },
	  { label: '毫升', value: '毫升' },
	  { label: 'IU', value: 'IU' },
	  { label: '杯', value: '杯' },
	  { label: '软', value: '软' },
	  { label: '粒', value: '粒' },
	  { label: '颗', value: '颗' },
	  { label: '袋', value: '袋' },
	  { label: '支', value: '支' },
	  { label: '瓶', value: '瓶' },
	  { label: '滴', value: '滴' },
	  { label: '匙', value: '匙' },
	  { label: '喷', value: '喷' },
	  { label: '吸', value: '吸' },
	  { label: '包', value: '包' },
	  { label: '微克', value: '微克' }
	],
	// 剂量弹窗相关
	showDosageDialog: false,
	currentDosage: {
	  value: '',
	  unit: ''
	},
	currentDosageIndex: -1,
  },
  
  onLoad: function(options) {
	  this.setData({
		  currentPerson:wx.getStorageSync('activeUser'),
		  dailyFrequencies:this.getFrequencyOptions('daily'),
		  dayIntervals:this.getFrequencyOptions('days'),
		  hourIntervals:this.getFrequencyOptions('hours'),
		  lengths:this.getDays()
	  })
    if (options.id) {
      // 编辑模式，加载已有数据
      this.setData({
        isEdit: true,
        planId: options.id
      });
      this.loadPlanData(options.id);
    } else {
      // 添加模式，设置默认开始日期为今天
      const today = this.formatDate(new Date());
      this.setData({
        'formData.start_date': today
      });
    }
  },
  getDays(){
	  return Array.from({length: 365}, (_, i) => `${i+1}天`);
  },
  getFrequencyOptions(type) {
  	  console.log(type)
  	  if (!type) return ['请先选择用药方案'];  	      
	  if (type === 'daily') {
		return Array.from({length: 4}, (_, i) => `每天${i+1}次`);
	  } else if (type === 'days') {
		return Array.from({length: 30}, (_, i) => `${i+1}天一次`);
	  } else if (type === 'hours') {
		return Array.from({length: 24}, (_, i) => `${i+1}小时一次`);
	  }
	  return [];
  },
  // 加载计划数据
  loadPlanData: function(id) {
    // 这里应该是从服务器获取数据，这里用模拟数据
    var that = this
      app.util.request({
    	  url: 'Medicalmanage/getMedicalPlanDetail',
    	  data: {id:id},
    	  success(res) {
    		  var data = res.data.data;
			  console.log('res',data)
    		  that.setData({
    		    formData: data
    		  });
    	  }
      })
    
  },
  
  
  // 选择开始日期
  changeStartDate: function(e) {
    this.setData({
      'formData.start_date': e.detail.value
    });
  },
  
  // 选择持续时间
  changeDuration: function(e) {
	  console.log('e.detail.value',e.detail.value)
    this.setData({
      'formData.length': this.data.lengths[e.detail.value].match(/\d/)[0],
	  'formData.duration':this.data.lengths[e.detail.value]
    });
  },
  
  // 选择用法
  changeUsage: function(e) {
    this.setData({
      'formData.method': this.data.methods[e.detail.value]
    });
  },
  
  // 切换用药方案类型
  changeSchemeType: function(e) {
    const type = parseInt(e.currentTarget.dataset.type);
    this.setData({
      'formData.scheme': type,
      'formData.num': '',
	  'formData.times':[''],
	  'formData.frequency':''// 切换类型时清空已选频率
    });
  },
  
  // 选择用药频率
  changeFrequency: function(e) {
    let frequency = '';
    if (this.data.formData.scheme === 0) {
      frequency = this.data.dailyFrequencies[e.detail.value];	  
    } else if (this.data.formData.scheme === 1) {
      frequency = this.data.dayIntervals[e.detail.value];
    } else {
      frequency = this.data.hourIntervals[e.detail.value];
    }
    this.setData({
      'formData.num': frequency.match(/\d/)[0],
	  'formData.frequency':frequency,
	  'formData.times':['']
    });
  },
  
  // 选择用药时间
  changeTime: function(e) {
    const index = e.currentTarget.dataset.index;
	const edit_time = e.currentTarget.dataset.time;
    const time = e.detail.value;
    const times = this.data.formData.times;
	if(edit_time != ''){//修改
		let selext_index = times.indexOf(edit_time)
		if(selext_index > -1){
			times.splice(selext_index,1,time)
		}else{
			if(this.data.formData.num > times.length -1 && this.data.formData.scheme == 0){
				times.unshift(time);    
			}else{
				times[0] = time
			}
		}
	}else{
		if(this.data.formData.num > times.length -1 && this.data.formData.scheme == 0){
			times.unshift(time);    
		}else{
			times[0] = time
		}
	}
	
    this.setData({
      'formData.times': times
    });
  },
  
  
  // 显示剂量弹窗
    showDosageDialog(e) {
    
      this.setData({
        showDosageDialog: true
      });
    },
  
    // 隐藏剂量弹窗
    hideDosageDialog() {
      this.setData({
        showDosageDialog: false
      });
    },
  
    // 输入剂量值
    inputDosageValue(e) {
      this.setData({
		'formData.metering':e.detail.value,
        'currentDosage.value': e.detail.value
      });
    },
	inputMedicationName(e){
		this.setData({
		  'formData.medication_name': e.detail.value
		});
	},
    // 选择剂量单位
    selectDosageUnit(e) {
      const unit = e.currentTarget.dataset.value;
      this.setData({
		'formData.metering_unit':unit,
        'currentDosage.unit': unit
      });
    },
  
    // 确认剂量
    confirmDosage() {
      const index = this.data.currentDosageIndex;
      this.setData({
		  'formData.metering':this.data.currentDosage.value,
		  'formData.metering_unit':this.data.currentDosage.unit,
        showDosageDialog: false
      });
    },
  
  // 选择用药指导
  changeInstruction: function(e) {
    this.setData({
      'formData.guidance': e.currentTarget.dataset.value
    });
  },
  
  // 输入备注
  inputRemark: function(e) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },
  
  // 提交表单
  submitForm: function(e) {
    const formData = this.data.formData;
    const currentPerson = this.data.currentPerson;
    
    // 简单验证
    if (!formData.medication_name) {
      wx.showToast({
        title: '请输入药品名称',
        icon: 'none'
      });
      return;
    }
    if (!formData.start_date) {
      wx.showToast({
        title: '请选择用药开始时间',
        icon: 'none'
      });
      return;
    }
	
    if (!formData.num) {
      wx.showToast({
        title: '请选择用药次数',
        icon: 'none'
      });
      return;
    }
	
	if (!formData.metering) {
	  wx.showToast({
	    title: '请选择用药剂量',
	    icon: 'none'
	  });
	  return;
	}
    // 构建提交数据
    const submitData = {
      family_id: currentPerson.id,
      ...formData
    };
	if(submitData.times.length > 0){
		let res_null_index = ''
		submitData.times.forEach(function(e){			
			if(e == ''){
				res_null_index = submitData.times.indexOf(e)
			}
		})
		if(res_null_index != ''){
			submitData.times.splice(res_null_index,1)
		}
	}
	if (submitData.times.length == 0) {
	  wx.showToast({
	    title: '请选择用药时间',
	    icon: 'none'
	  });
	  return;
	}
	console.log(submitData.scheme)
	console.log(submitData.times)
	console.log(submitData.times.length)
	console.log(submitData.num)
	if(submitData.scheme == 0 && submitData.times.length < submitData.num){
		wx.showToast({
		  title: '用药时间选择有误',
		  icon: 'none'
		});
		return;
	}
    console.log('提交数据:', submitData);
	 const that = this;
      // 模拟保存操作
      wx.showLoading({
        title: '保存中...',
      });
      let jsonData = JSON.stringify(submitData);
      app.util.request({
      	url: 'Medicalmanage/createMedicalPlanData',
      	data: jsonData,
      	method:'POST',
      	headers: {
      		'Content-Type': 'application/json',
      	},
      	success(res) {
      		console.log(res)
      		if(res.data.code){	
				wx.hideLoading();
				wx.showToast({
				  title: '保存成功',
				  icon: 'success'
				});	
				setTimeout(() => {
				  wx.navigateBack();
				}, 1500);
      		}else{
      			wx.showToast({ title: '提交失败请重试' });
      		}
      	}
      })
  },
  
  // 格式化日期为YYYY-MM-DD
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
});